/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  QunZuAddActivity.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-13 上午10:24:25   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jiyi.activity.LActivity;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.QunZuListEvent;
import com.jiyi.inteface.PickPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.PickPopView;
import com.jiyi.widget.PopTextView;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.SysUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: QunZuAddActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-13 上午10:24:25
 * 
 */
public class QunZuCreateActivity extends LActivity implements
		PickPopInterface {

	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.ivLogo)
	ImageView ivLogo;
	@BindView(R.id.ptvState)
	PopTextView ptvState;
	@BindView(R.id.root)
	LinearLayout root;
	@BindView(R.id.llPick)
	LinearLayout llPick;
	@BindView(R.id.tvInvite)
	TextView tvInvite;
	@BindView(R.id.etQunZuName)
	EditText etQunZuName;
	@BindView(R.id.etQunZuJieShao)
	EditText etQunZuJieShao;
	@BindView(R.id.tvCreator)
	TextView tvCreator;

	ArrayAdapter<String> stateAdapter;

	PickPopView mPickPopView;

	// 图片路径
	private Uri CameraUri;
	// 拍摄事件
	public final int CAMARE_CODE = 1;
	// 从相册选择事件
	public final int CHOOSE_PICTURE = 2;
	// 邀请好友事件
	public final int INVITE_FRIEND = 3;

	// 图片路径
	private String filePath;

	// 保存当前选择的id
	ArrayList<String> idsList = new ArrayList<String>();
	// 进度条
	Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qunzu_create);
		ButterKnife.bind(this);
		init();
	}

	@Override
	public void onBackPressed() {
		onBackActivity(root);
	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	@Override
	public void onAnimatStop() {
		finish();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-8
	 */
	private void init() {
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
			//获取前面点击的对象
			x = getIntent().getIntExtra("x", 0);
			y = getIntent().getIntExtra("y", 0);
			//初始化开场动画和退场动画
			setupAnimator(root,x,y);
		}

		setViewStatus();
		setTop();
		setStateAdapter();
		mPickPopView = new PickPopView(this, this);
	}

	private void setViewStatus() {
		// 设置必填项检测提示
		etQunZuName.setTag(R.id.tag_view_empty, "群组名称不能为空");
		etQunZuJieShao.setTag(R.id.tag_view_empty, "群组介绍不能为空");

		// 设置群组名称
		tvCreator.setText(ApplicationBase.LocalData.getString("user_name", ""));
	}

	/**
	 * @author: HYM
	 * @Title: setTop
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-9
	 */
	private void setTop() {
		tvBack.setText("");
		tvTitle.setText("创建群组");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("创建");
	}

	/**
	 * @author: HYM
	 * @Title: setStateAdapter
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-9
	 */
	private void setStateAdapter() {
		// 设置报修状态的适配器
		stateAdapter = new ArrayAdapter<String>(this,
				R.layout.item_huodong_join_state, getResources()
						.getStringArray(R.array.qunzu_join_state));
		ptvState.setListAdapter(stateAdapter);
		ptvState.setOnItemClick(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ptvState.doListItemClick(
						((TextView) view).getText().toString(), position + "");
			}
		});
	}

	@Override
	public void OnShootListener() {
		if(PermissionUtil.checkPermission(this,PermissionUtil.CARAME))
		{
			useCamere();
		}
	}

	@Override
	public void OnAlbumListener() {
		Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
		openAlbumIntent.setType("image/*");
		startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
		mPickPopView.hidePopWindow();
	}

	/**
	 * <p>
	 * Title: OnCancleListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnCancleListener()
	 */
	@Override
	public void OnCancleListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnShowListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnHideListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * @author: HYM
	 * @Title: hideChoose
	 * @Description: TODO(logo在选择完成后，隐藏之前的选择提示，并设置当前Logo可以点击重新选择) void
	 * @date: 2017-6-13
	 */
	void hideChoose() {
		llPick.setVisibility(View.GONE);
		ivLogo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPickPopView.showPopWindow();
			}
		});
	}

	@OnClick({ R.id.tvBack, R.id.llPick, R.id.tvInvite, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			onBackActivity(root);
			break;
		case R.id.llPick:
			mPickPopView.showPopWindow();
			break;
		case R.id.tvInvite:
			Intent intent = new Intent(this, QunZuInviteActivity.class);
			intent.putStringArrayListExtra("join_friend", idsList);
			intent.putExtra("from", "qunzu_create");
			startActivityForResult(intent, INVITE_FRIEND);
			break;
		case R.id.tvSearch:
			if (TextUtils.isEmpty(filePath)) {
				ToastUtil.getInstances().showMsg("请先选择封面");
				return;
			}
			if (CheckUtil.checkView(etQunZuName, etQunZuJieShao)) {
				// 执行创建操作
				doPost();
			}

			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMARE_CODE && resultCode == RESULT_OK) {
			try {
				Glide.with(this).load(new File(filePath)).into(ivLogo);
				hideChoose();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (requestCode == CHOOSE_PICTURE) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri temp = data.getData();
					filePath = CameraUtils.getImageAbsolutePath(this, temp);
					Glide.with(this).load(new File(filePath)).into(ivLogo);
					hideChoose();
				}

			}
		} else if (requestCode == INVITE_FRIEND) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					int max = data.getIntExtra("max", 0);
					ArrayList<String> join_friend = data
							.getStringArrayListExtra("join_friend");
					if (join_friend != null) {
						idsList.clear();
						idsList.addAll(join_friend);
						tvInvite.setText(idsList.size() + "/" + max);
					}
				}
			}
		}

	}

	private void doPost() {
		String webApi = WebApi.ZONE_QUNZU_CREATE;

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("name", etQunZuName.getText().toString());
		params.put("introduction", etQunZuJieShao.getText().toString());
		params.put("group_manager_nickname", tvCreator.getText().toString());
		params.put("group_manager_id", ApplicationBase.LocalData.getInt(AppConfig.USER_ID, 0)+"");
		params.put("group_type", ptvState.getSelectedId());
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < idsList.size(); i++) {
			sb.append(idsList.get(i));
			sb.append(",");
		}
		String userList = SysUtils.SbToString(sb);
		
		if (!TextUtils.isEmpty(userList)) {
			params.put("friends", userList);
		}
		

		PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
		postForm.params(params);
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);
			postForm.addFile("group_head", "qunzu_logo.jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().connTimeOut(60000)
	    .readTimeOut(60000)
	    .writeTimeOut(60000).execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						setResult(RESULT_OK);
						EventBus.getDefault().post(
								new QunZuListEvent(
										QunZuListEvent.MY_QUNZU_FRAGMENT));
						Log.d("post huodong event ", " MY_HUODONG_FRAGMENT");
						onBackActivity(root);
					} 
					else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
						//清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context, true);
						return;
					}
					else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}

	private void useCamere()
	{
		File fileDir = new File(AppConfig.DIR_IMAGE);
		if (!fileDir.exists())
		{
			fileDir.mkdirs();
		}

		filePath = AppConfig.DIR_IMAGE+"temp"+new Date().getTime()+".jpg";
		File file = new File(filePath);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
		{
			CameraUri = FileProvider.getUriForFile(this,"com.swift.maintenance.updateprovider",file);
		}
		else
		{
			CameraUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
			filePath=CameraUri.getPath();
		}
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");



		intent.putExtra(MediaStore.EXTRA_OUTPUT, CameraUri);
		startActivityForResult(intent, CAMARE_CODE);
		mPickPopView.hidePopWindow();
	}


	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == PermissionUtil.CARAME)
		{
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
			{
				useCamere();
			}
			else
			{
				ToastUtil.getInstances().showMsg("无法访问相机");
			}
		}
	}
}
